package com.aat.dxfy.string;

import java.io.BufferedReader;
import java.io.FileReader;

/**
 * 格式化输入工具类
 * 
 * @author able
 *
 */
public final class FormatUtil {
	
	public static void main(String[] args) throws Exception {
		//{"respData":"AQAAACO0TqpITiXhqDHU1VvKyZ/zPw4lWLBZEN+7fxkujbBVm9+sH620uDeTf8TMlT/xGDOc5j6VhlFbFEev33TqAs1b7c12cBfMSehna5W2B51dclte5ZQEpn+m77sj7hlXNvOljh2bWKmrl5MWrfBaKzyFUyN07OrDhNeKog+mq3Rgpwr7vZevdP4v5pSLehJJl2oqF/0SjiUDiUPi8tKWfXUhznca1044GhBI6PM2aQR4gCRnj+IsVBHZ1rk/qYvUA8qtcoaaJFiDUWCwenx/J/YKnpbkBmqoYqR+CITJu88d+v484rH31MxGb8+l0bSy48SVrZTDaFCurnxhRk3a8kNHJ5X+03Ctu/wKoERVup1AprYJPHH/CRLGQ/BG1c6kuDq+eAdDP6QpRUokGN0eWmb4oKev0PoXXvFKvOFbvIC81yAroZUJBN/zpBLdhp53BFcrAiRFUjS/IW7lf/IPxns5DtiduyBJJO3wePEnqmww","respType":"unbind","status":0,"statusMsg":"success"}
		BufferedReader br=new BufferedReader(new FileReader("E:\\WWWXXX\\aatJavaSrc\\git01_aatTools\\aatTools\\src\\main\\java\\com\\aat\\dxfy\\string\\test.json"));
		String jsonStr=br.readLine();
		printJson(jsonStr);
		br.close();
	}

	/**
	 * 打印输入到控制台
	 * 
	 * @param jsonStr
	 * @author able
	 * @Date 2015-10-14 下午1:17:22
	 */
	public static void printJson(String jsonStr) {
		System.out.println(formatJson(jsonStr));
	}

	/**
	 * 格式化
	 * 
	 * @param jsonStr
	 * @return
	 * @author able
	 * @Date 2015-10-14 下午1:17:35
	 */
	public static String formatJson(String jsonStr) {
		if (null == jsonStr || "".equals(jsonStr))
			return "";
		StringBuilder sb = new StringBuilder();
		char last = '\0';
		char current = '\0';
		int indent = 0;
		for (int i = 0; i < jsonStr.length(); i++) {
			last = current;
			current = jsonStr.charAt(i);
			switch (current) {
			case '{':
			case '[':
				sb.append(current);
				sb.append('\n');
				indent++;
				addIndentBlank(sb, indent);
				break;
			case '}':
			case ']':
				sb.append('\n');
				indent--;
				addIndentBlank(sb, indent);
				sb.append(current);
				break;
			case ',':
				sb.append(current);
				if (last != '\\') {
					sb.append('\n');
					addIndentBlank(sb, indent);
				}
				break;
			default:
				sb.append(current);
			}
		}

		return sb.toString();
	}

	/**
	 * 添加space
	 * 
	 * @param sb
	 * @param indent
	 * @author able
	 * @Date 2015-10-14 上午10:38:04
	 */
	private static void addIndentBlank(StringBuilder sb, int indent) {
		for (int i = 0; i < indent; i++) {
			sb.append('\t');
		}
	}
}